/*
 * @Author: 王国涛
 * @Date: 2022-07-01 18:15:24
 * @Last Modified by: 王国涛
 * @Last Modified time: 2022-07-07 18:12:30
 */
//加载本地文件专用
interface window {
  localFileElement: any;
}

/**
 *
 * @param rootDir 判断路径是否已经挂载
 * @returns
 */
function getExists(rootDir: string) {
  const mounts = window.Module.FS.root.mount.mounts;
  let res = false;
  mounts.forEach((mount: any) => {
    if (mount.opts.root) {
      const root = mount.opts.root;
      if (root.indexOf(rootDir) > -1) {
        res = true;
      }
    }
  });
  return res;
}

/**
 *
 * @param add 添加本地文件
 * @returns
 */
export const nativeAdd = (add: any) => {
  window.localFileElement.click();
  const inputElement = window.localFileElement;
  return new Promise((resolve, reject) => {
    inputElement.onchange = (e: any) => {
      //全局挂载
      console.log("重新挂载");
      const file0 = e.target.files[0];
      let originPath = file0.path;
      const rootDir = originPath.split(":\\")[0];
      const dirPath = originPath.split(":\\")[1];

      if (!getExists(rootDir)) {
        window.Module.FS.mkdir(`/device_${rootDir}`);
        window.Module.FS.mount(
          window.Module.NODEFS,
          { root: `${rootDir}:` },
          `/device_${rootDir}`
        );
      }

      let url = `/device_${rootDir}/` + dirPath.replaceAll("\\", "/");
      resolve(add(url, originPath));
    };
  });
};
